//
//  NewsTableViewController.m
//  CaiJing
//
//  Created by 6009 on 15/11/17.
//  Copyright © 2015年 OC_2_1. All rights reserved.
//

#import "NewsTableViewController.h"
#import "SrcollViewTableViewCell.h"
#import "NumberTableViewCell.h"
#import "DefaultTableViewCell.h"
#import "ButtonHeaderView.h"
#import "GetXMLObject.h"
#import "NEWSModel.h"
#import "StockModel.h"
#import "XMLModel.h"
#import "UIImageView+WebCache.h"
#import "TextViewController.h"
#import "MBProgressHUD.h"
#import "NEWSVideoTableViewController.h"
#import "UIButton+WebCache.h"
#import "StockInfoModelViewController.h"
@interface NewsTableViewController ()<ButtonHeaderViewDelegate,UIScrollViewDelegate>
{
    //头条的区头数组
    NSArray *_headerArr;
    //记录全部数据的字典
    NSDictionary* _dataDic;
    //记录每个数据的数组
    NSArray *_dataArr;
    //根据tag的值更换数据
    NSInteger _buttonTag;
    
    
    //每个界面的数据数组
    NSArray* _stockNewsArr;
    NSArray* _fundNewsArr;
    NSArray* _futuresNewsArr;
    NSArray* _futuresIndexNewsArr;
    NSArray* _goldNewsArr;
    NSArray* _forexNewsArr;
    NSArray* _bondsNewsArr;
    NSArray* _commentNewsArr;
    NSArray* _manageMoneyNewsArr;
    NSArray* _bankNewsArr;
    NSArray* _serverNewsArr;
    NSArray* _houseNewsArr;
    NSArray* _carNewsArr;
    NSArray* _technologyNewsArr;
    NSArray* _readingNewsArr;
    NSArray* _forexArr;
    
    __weak IBOutlet UIScrollView *_headerScroll;
    
    __weak IBOutlet UIButton *toutiao;
    __weak IBOutlet UIButton *gupiao;
    __weak IBOutlet UIButton *jijin;
    __weak IBOutlet UIButton *qihuo;
    __weak IBOutlet UIButton *qizhi;
    __weak IBOutlet UIButton *huangjin;
    __weak IBOutlet UIButton *waihui;
    __weak IBOutlet UIButton *zaijuan;
    __weak IBOutlet UIButton *pinglun;
    __weak IBOutlet UIButton *licai;
    __weak IBOutlet UIButton *yinhang;
    __weak IBOutlet UIButton *baoxian;
    __weak IBOutlet UIButton *fangchang;
    __weak IBOutlet UIButton *qiche;
    __weak IBOutlet UIButton *keji;
    __weak IBOutlet UIButton *dushu;
    __weak IBOutlet UIButton *shipin;
    //全部导航栏的按钮
    NSArray *_buttonArr;
}
@end

@implementation NewsTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tabBarController.navigationItem.rightBarButtonItem = self.navigationItem.rightBarButtonItem;
    self.tabBarController.navigationItem.leftBarButtonItem = self.navigationItem.leftBarButtonItem;
    self.tabBarController.navigationItem.titleView = self.navigationItem.titleView;
    self.tabBarController.navigationItem.title = self.navigationItem.title;
    
    
    //数据请求
    [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
    NSBlockOperation* cOperation = [NSBlockOperation blockOperationWithBlock:^{
        
        GetXMLObject* xmlObject = [GetXMLObject new];
        //请求头条
        [xmlObject getXMLData:@"http://wiapi.hexun.com/news/gethp.php?id=100234721"];
        //请求股票
        _stockNewsArr = [xmlObject getOtherNewsModelArray:@"100228599"];
        //请求基金
        _fundNewsArr = [xmlObject getOtherNewsModelArray:@"101767368"];
        //请求期货
        _futuresNewsArr = [xmlObject getOtherNewsModelArray:@"101032758"];
        //请求期指
        _futuresIndexNewsArr = [xmlObject getOtherNewsModelArray:@"101155325"];
        //请求黄金
        _goldNewsArr = [xmlObject getOtherNewsModelArray:@"101710857"];
        //请求外汇
        _forexNewsArr = [xmlObject getOtherNewsModelArray:@"100098426"];
        //债卷
        _bondsNewsArr = [xmlObject getOtherNewsModelArray:@"101032723"];
        //评论
        _commentNewsArr = [xmlObject getOtherNewsModelArray:@"100012296"];
        //理财
        _manageMoneyNewsArr = [xmlObject getOtherNewsModelArray:@"101002114"];
        //银行
        _bankNewsArr = [xmlObject getOtherNewsModelArray:@"101710894"];
        //保险
        _serverNewsArr = [xmlObject getOtherNewsModelArray:@"101710721"];
        //房产
        _houseNewsArr = [xmlObject getOtherNewsModelArray:@"100092115"];
        //汽车
        _carNewsArr = [xmlObject getOtherNewsModelArray:@"101931837"];
        //科技
        _technologyNewsArr = [xmlObject getOtherNewsModelArray:@"100052214"];
        //读书
        _readingNewsArr = [xmlObject getOtherNewsModelArray:@"103147590"];
        
        //外汇行情
        
       
        _forexArr = [xmlObject getExchangeQuotationsArray];
        _dataDic = @{@"0":@[xmlObject.resultArray[3],_bondsNewsArr[1],_readingNewsArr[1],_goldNewsArr[1]],
                     @"1":_forexArr,
                     @"2":xmlObject.resultArray,
                     @"3":_stockNewsArr,
                     @"4":_fundNewsArr,
                     @"5":_futuresNewsArr,
                     @"6":_futuresIndexNewsArr,
                     @"7":_goldNewsArr,
                     @"8":_forexNewsArr,
                     @"9":_bondsNewsArr,
                     @"10":_commentNewsArr,
                     @"11":_manageMoneyNewsArr,
                     @"12":_bankNewsArr,
                     @"13":_serverNewsArr,
                     @"14":_houseNewsArr,
                     @"15":_carNewsArr,
                     @"16":_technologyNewsArr,
                     @"17":_readingNewsArr
                     };
        
        NSBlockOperation* dOperation = [NSBlockOperation blockOperationWithBlock:^{
            [self.tableView reloadData];
            [MBProgressHUD hideHUDForView:self.tableView animated:YES];
        }];
        //涉及更新UI的操作，就要创建包含这些操作的Operation对象，并把它放入主线程队列
        NSOperationQueue* mainQueue = [NSOperationQueue mainQueue];
        //当Operation放入主线程队列中，其操作就是子主线程中执行
        [mainQueue addOperation:dOperation];
    }];
    
    //创建Operation队列,operation只有在队列里才能跑
    NSOperationQueue* takeMoneyQueue = [NSOperationQueue new];
    [takeMoneyQueue addOperation:cOperation];
    
    
    
    //只用于头条的数组
    _headerArr = [NSArray new];
    _headerArr = @[@"scrollView",@"numberview",@"头条",@"股票",@"基金",@"期货",@"期指",@"黄金",@"外汇",@"债劵",@"评论",@"理财",@"银行",@"保险",@"房产",@"汽车",@"科技",@"读书"];
    [self.tableView registerClass:[ButtonHeaderView class] forHeaderFooterViewReuseIdentifier:@"header"];
    
    //导航栏按钮的功能实现
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(action:) name:@"buttonPress" object:nil];
    _buttonArr = @[toutiao,gupiao,jijin,qihuo,qizhi,huangjin,waihui,zaijuan,pinglun,licai,yinhang,baoxian,fangchang,qiche,keji,dushu,shipin];
    
    self.tableView.tag = 111;
    
    
}

#pragma mark - 数据源代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_buttonTag != 0 && _buttonTag != 16){
        return 1;
    }else{
    //判断如果是是否头条才给分区
        if ( _buttonTag == 0 ){
            return _headerArr.count;
        }else{
            return 0;
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_buttonTag != 0 && _buttonTag != 16){
        return _dataArr.count;
    }else{
        if ( section == 0 || section == 1 ){
            return 1;
        }else{
            return 4;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GetXMLObject* xmlObject = [GetXMLObject new];
    if (_buttonTag != 0 && _buttonTag != 16)
    {
        DefaultTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"default"];
        
        XMLModel* news = _dataArr[indexPath.row];
        if (news != nil)
        {
            NSBlockOperation* cOperation = [NSBlockOperation blockOperationWithBlock:^{
                NEWSModel* newModel = [xmlObject getSomeoneNewFromNewsID:news.ID];
                
                NSBlockOperation* dOperation = [NSBlockOperation blockOperationWithBlock:^{
                    if (![newModel.matchpic isEqualToString:@""])
                    {
                        [cell.imgView sd_setImageWithURL:[NSURL URLWithString:newModel.matchpic]];
                    }
                    cell.nameLabel.text = news.ID;
                    cell.dateLabel.text = news.date;
                    cell.title.text = news.title;
                    
                }];
                //涉及更新UI的操作，就要创建包含这些操作的Operation对象，并把它放入主线程队列
                NSOperationQueue* mainQueue = [NSOperationQueue mainQueue];
                //当Operation放入主线程队列中，其操作就是子主线程中执行
                [mainQueue addOperation:dOperation];
            }];
            
            //创建Operation队列,operation只有在队列里才能跑
            NSOperationQueue* takeMoneyQueue = [NSOperationQueue new];
            
            [takeMoneyQueue addOperation:cOperation];
        }
        return cell;
    }
    else
    {
        if ( indexPath.section == 0 )
        {
            ScrollViewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"scroll"];
            cell.scrollView.delegate = self;
            
            if (_dataDic != nil)
            {
            XMLModel* newsModel1 = _dataDic[[NSString stringWithFormat:@"%ld",(long)indexPath.section]][0];
            XMLModel* newsModel2 = _dataDic[[NSString stringWithFormat:@"%ld",(long)indexPath.section]][1];
            XMLModel* newsModel3 = _dataDic[[NSString stringWithFormat:@"%ld",(long)indexPath.section]][2];
            XMLModel* newsModel4 = _dataDic[[NSString stringWithFormat:@"%ld",(long)indexPath.section]][3];
            NSBlockOperation* cOperation = [NSBlockOperation blockOperationWithBlock:^{
                NEWSModel* newModel1 = [xmlObject getSomeoneNewFromNewsID:newsModel1.ID];
                NEWSModel* newModel2 = [xmlObject getSomeoneNewFromNewsID:newsModel2.ID];
                NEWSModel* newModel3 = [xmlObject getSomeoneNewFromNewsID:newsModel3.ID];
                NEWSModel* newModel4 = [xmlObject getSomeoneNewFromNewsID:newsModel4.ID];
                NSBlockOperation* dOperation = [NSBlockOperation blockOperationWithBlock:^{
                    [cell.button1 sd_setBackgroundImageWithURL:[NSURL URLWithString:[xmlObject getStrArrFrom:newModel1.matchpic using:@","].firstObject] forState:UIControlStateNormal];
                    [cell.button2 sd_setBackgroundImageWithURL:[NSURL URLWithString:[xmlObject getStrArrFrom:newModel2.matchpic using:@","].firstObject] forState:UIControlStateNormal];
                    [cell.button3 sd_setBackgroundImageWithURL:[NSURL URLWithString:[xmlObject getStrArrFrom:newModel3.matchpic using:@","].firstObject] forState:UIControlStateNormal];
                    [cell.button4 sd_setBackgroundImageWithURL:[NSURL URLWithString:[xmlObject getStrArrFrom:newModel4.matchpic using:@","].firstObject] forState:UIControlStateNormal];
                    
                    cell.label1.text = newsModel1.title;
                    cell.label2.text = newsModel2.title;
                    cell.label3.text = newsModel3.title;
                    cell.label4.text = newsModel4.title;
    
                }];
                //涉及更新UI的操作，就要创建包含这些操作的Operation对象，并把它放入主线程队列
                NSOperationQueue* mainQueue = [NSOperationQueue mainQueue];
                //当Operation放入主线程队列中，其操作就是子主线程中执行
                [mainQueue addOperation:dOperation];
            }];
            
            //创建Operation队列,operation只有在队列里才能跑
            NSOperationQueue* takeMoneyQueue = [NSOperationQueue new];
            
            [takeMoneyQueue addOperation:cOperation];
            
            }
            return cell;
        }
        else if ( indexPath.section == 1)
        {
            NumberTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"number"];
            StockModel* stockModel1 = _dataDic[[NSString stringWithFormat:@"%ld",(long)indexPath.section]][0];
            StockModel* stockModel2 = _dataDic[[NSString stringWithFormat:@"%ld",(long)indexPath.section]][1];
            StockModel* stockModel3 = _dataDic[[NSString stringWithFormat:@"%ld",(long)indexPath.section]][2];
            cell.shangLabel.text = stockModel1.fld_index;
            cell.chuangLabel.text = stockModel2.fld_index;
            cell.shenLabel.text = stockModel3.fld_index;
            [cell.shangbutton setTitle:stockModel1.fld_value forState:UIControlStateNormal];
            [cell.chuangButton setTitle:stockModel2.fld_value forState:UIControlStateNormal];
            [cell.shenButton setTitle:stockModel3.fld_value forState:UIControlStateNormal];
            return cell;
        }
        else
        {
            DefaultTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"default"];
            NSArray* array = _dataDic[[NSString stringWithFormat:@"%ld",(long)indexPath.section]];
            XMLModel* news = array[indexPath.row];
            if (news != nil)
            {
                NSBlockOperation* cOperation = [NSBlockOperation blockOperationWithBlock:^{
                    NEWSModel* newModel = [xmlObject getSomeoneNewFromNewsID:news.ID];
                    
                    NSBlockOperation* dOperation = [NSBlockOperation blockOperationWithBlock:^{
                        if (![newModel.matchpic isEqualToString:@""])
                        {
                            [cell.imgView sd_setImageWithURL:[NSURL URLWithString:newModel.matchpic]];
                        }
                        cell.nameLabel.text = news.ID;
                        cell.dateLabel.text = news.date;
                        cell.title.text = news.title;
                        
                    }];
                    //涉及更新UI的操作，就要创建包含这些操作的Operation对象，并把它放入主线程队列
                    NSOperationQueue* mainQueue = [NSOperationQueue mainQueue];
                    //当Operation放入主线程队列中，其操作就是子主线程中执行
                    [mainQueue addOperation:dOperation];
                }];
                
                //创建Operation队列,operation只有在队列里才能跑
                NSOperationQueue* takeMoneyQueue = [NSOperationQueue new];
                
                [takeMoneyQueue addOperation:cOperation];
                
                
            }
            return cell;
        }
    }
}


#pragma mark - 设置表视图分区头的代理方法
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if ( _buttonTag != 0 && _buttonTag != 16 ){
        return nil;
    }else{
        
    ButtonHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    header.buttonTitle = _headerArr[section];
    header.delegate = self;
    header.tag = section;
        
    return header;
    }
}

-(void)buttonHeaderViewDidPress:(ButtonHeaderView *)buttonHeaderView{
     [[NSNotificationCenter defaultCenter] postNotificationName:@"buttonPress" object:buttonHeaderView];
    [self.tableView setContentOffset:CGPointMake(0,-64) animated:NO];
     NSLog(@"%@区头点击",buttonHeaderView.buttonTitle);
}

#pragma mark - 设置行区高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (_buttonTag != 0 && _buttonTag != 16){ return 1;}
    else{
        if ( section == 0 || section == 1 || section == 2 ){ return 0;}
        else{ return 30;}
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_buttonTag != 0 && _buttonTag != 16){ return 100;}
    else{
        if ( indexPath.section == 0 ){ return 200;}
        else{ return 100;}
    }
}

#pragma mark - 通知
-(void)action:(NSNotification*)notification{
    //点导航栏的按钮
    if ([notification.object isKindOfClass:[UIButton class]])
    {
        UIButton *button = notification.object;
        //改变字体
        button.titleLabel.font = [UIFont boldSystemFontOfSize:20];
        [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        for ( UIButton *bo  in _buttonArr) {
            if ( bo.tag != button.tag ) {
                bo.titleLabel.font = [UIFont boldSystemFontOfSize:16];
                [bo setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            }
        }
        if ( button.tag != 0 && button.tag != 1 && button.tag != 15 && button.tag != 16 ) {
            [_headerScroll setContentOffset:CGPointMake(50 * ( button.tag - 2 ), 0) animated:YES];
        }

        _buttonTag = button.tag;
        NSLog(@"%ld",(long)button.tag);
        if (_buttonTag == 0)
        {
            [self.tableView reloadData];
        }
        else if(_buttonTag != 0 && _buttonTag != 16)
        {
            _dataArr = _dataDic[[NSString stringWithFormat:@"%d",_buttonTag+2]];
            [self.tableView reloadData];
        }
    }
    //点区头的按钮
    if ([notification.object isKindOfClass:[ButtonHeaderView class]])
    {
        ButtonHeaderView* buttonHeaderView = notification.object;
        
        UIButton *button = _buttonArr[buttonHeaderView.tag - 2];
        
        //改变字体
        button.titleLabel.font = [UIFont boldSystemFontOfSize:20];
        [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        for ( UIButton *bo  in _buttonArr ) {
            if ( bo.tag != button.tag ) {
                bo.titleLabel.font = [UIFont boldSystemFontOfSize:16];
                [bo setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            }
        }
        if ( button.tag != 0 && button.tag != 1 && button.tag != 15 && button.tag != 16 ) {
            [_headerScroll setContentOffset:CGPointMake(50 * ( button.tag - 2 ), 0) animated:YES];
        }
        
        if ([buttonHeaderView.buttonTitle isEqualToString:@"头条"])
        {
            _buttonTag = buttonHeaderView.tag;
            [self.tableView reloadData];
        }
        else if(![buttonHeaderView.buttonTitle isEqualToString:@"头条"] && ![buttonHeaderView.buttonTitle isEqualToString:@"视频"])
        {
            _buttonTag = buttonHeaderView.tag;
            _dataArr = _dataDic[[NSString stringWithFormat:@"%ld",(long)buttonHeaderView.tag]];
            [self.tableView reloadData];
        }
    }
}

- (IBAction)navigationButtonPress:(UIButton *)sender {
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"buttonPress" object:sender];
    _buttonTag = sender.tag;
    [self.tableView setContentOffset:CGPointMake(0,-64) animated:NO];
    NSLog(@"%@tag:%ld",sender.titleLabel.text,(long)sender.tag);
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"buttonPress" object:nil];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.tag == 0) {
        float width = scrollView.frame.size.width;
        float current = scrollView.contentOffset.x;
        float temp =  current/width;
        if (temp > 3.2) {
            CGPoint point = scrollView.bounds.origin;
            point.x = 0;
            scrollView.contentOffset = point;
        }
    }
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    UIButton* button = sender;
    if (button.tag == 16)
    {
       
    }
    if (button.tag == 71)
    {
        StockInfoModelViewController* stockInfoModelViewController = segue.destinationViewController;
        StockModel* stockModel1 = _dataDic[@"1"][0];
        stockInfoModelViewController.pointArr = stockModel1;
        stockInfoModelViewController.segmentIndex = 4;
    }
    if (button.tag == 72)
    {
        StockInfoModelViewController* stockInfoModelViewController = segue.destinationViewController;
        StockModel* stockModel1 = _dataDic[@"1"][1];
        stockInfoModelViewController.pointArr = stockModel1;
        stockInfoModelViewController.segmentIndex = 4;
    }
    if (button.tag == 73)
    {
        StockInfoModelViewController* stockInfoModelViewController = segue.destinationViewController;
        StockModel* stockModel1 = _dataDic[@"1"][2];
        stockInfoModelViewController.pointArr = stockModel1;
        stockInfoModelViewController.segmentIndex = 4;
    }
    if (button.tag != 73 && button.tag != 72 && button.tag != 71 && button.tag != 16)
    {
        TextViewController* textViewController = segue.destinationViewController;
        if (_buttonTag != 0 && _buttonTag != 16){
            textViewController.xmlModel = _dataArr[[self.tableView indexPathForSelectedRow].row];
        }else{
            
            if ([self.tableView indexPathForSelectedRow].section == 0){
                if(button.tag == 100){
                    textViewController.xmlModel = _dataDic[@"0"][0];
                }if(button.tag == 101){
                    textViewController.xmlModel = _dataDic[@"0"][1];
                }if(button.tag == 102){
                    textViewController.xmlModel = _dataDic[@"0"][2];
                }if(button.tag == 103){
                    textViewController.xmlModel = _dataDic[@"0"][3];
                }
            }else{
                NSString* section1 = [NSString stringWithFormat:@"%d",[self.tableView indexPathForSelectedRow].section];
                NSInteger row1 = [self.tableView indexPathForSelectedRow].row;
                XMLModel* xmlModel = _dataDic[section1][row1];
                textViewController.xmlModel = xmlModel;
            }
        }
    }
}


#pragma mark - itemDelegate
-(void)navigationItemToTabarControllerItem
{
    self.tabBarController.navigationItem.rightBarButtonItem = self.navigationItem.rightBarButtonItem;
    self.tabBarController.navigationItem.leftBarButtonItem = self.navigationItem.leftBarButtonItem;
    self.tabBarController.navigationItem.titleView = self.navigationItem.titleView;
    self.tabBarController.navigationItem.title = self.navigationItem.title;
    self.navigationController.navigationBarHidden = NO;
}

@end
